package com.test.demo.javabasis.jdk;


import java.io.FileInputStream;
import java.lang.reflect.Method;

public class MyClassLoader extends ClassLoader {
    private static String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    public static byte[] loadByte(String name) throws Exception {
        String s = name.replaceAll("\\.", "/");
        FileInputStream fileInputStream = new FileInputStream(classPath+s+".class");
        int len = fileInputStream.available();
        byte[] bytes = new byte[len];
        fileInputStream.read(bytes);
        fileInputStream.close();
        return bytes;
    }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            System.out.println("-------------自定义类加载器加载"+name+"----------------");
            byte[] bytes = loadByte(name);
            return defineClass(name,bytes,0,bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClassNotFoundException("自定义类加载器没加载到");
        }
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        ClassLoader system = getParent(); // appclass.parent=ext

        Class<?> clazz = null;
        try {
            clazz = system.loadClass(name);
        } catch (Exception e) {

        }

        if (clazz != null) {
            return clazz;
        }

        clazz = findClass(name);

        return clazz;
    }

    public static void main(String[] args) throws Exception {
        //MyClassLoader myClassLoader = new MyClassLoader("D:\\");
        MyClassLoader myClassLoader = new MyClassLoader("C:\\workspace\\mydemo\\javabasis\\target\\classes\\");
        Class<?> aClass = myClassLoader.loadClass("com.test.demo.javabasis.date.Test");
        Object o = aClass.newInstance();
        Method method = aClass.getMethod("test");
        method.invoke(o);
        System.out.println(o.getClass().getClassLoader());
    }
}
